import axios from "axios";
import { useSpinStore } from '@/store/spin'
// import { Message, Loading } from "element-ui";
// import { BASE_URL } from "./index";
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL
axios.defaults.timeout = 20000;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
const http = axios.create();

const post = http.post;
const get = http.get;
http.post = (url, params, options = {}, config) => {
  return post(
    url,
    params,
    config
  ).then((data = {}) => {
    return Promise.resolve(data.data);
  });
};

http.get = (url, params, options = {}, config) => {
  return get(
    url,
    {
      params,
      ...config
    }
  ).then((data = {}) => {
    return Promise.resolve(data.data ? data.data : false);
  });
};

let reqNum = 0;
const store = useSpinStore()
const startLoading = () => {
  if (reqNum === 0) {
    //loading开始
    store.updateLoadingFlag(1)
  }
  reqNum++;
};
const endLoading = () => {
  if (reqNum <= 0) {
    return;
  }
  reqNum--;
  if (reqNum === 0) {
    //loading结束
    store.updateLoadingFlag(0)
  }
};

// 请求拦截器
http.interceptors.request.use(
  config => {
    startLoading();
    let token = window.localStorage.getItem("token");
    config.headers.token = token;
    return config;
  },
  error => {
    endLoading();

    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  response => {
    endLoading();

    if (response.data.code == 200) {
      // 成功
      // loading.close();
      // console.log(response)
      return response;
    } else if (response.data.code == 401) {
      // token
      // loading.close();
      window.localStorage.clear();
      window.$message.error("登录过期,请重新登录");
      location.href = "/";
    } else {
      if (response.config.responseType == "blob") {
        // loading.close();
        return response;
      } else {
        window.$message.error(
          response.data.message ||
          "数据加载失败，请刷新页面重试！"
        );
        return Promise.reject(
          response.data.message || "数据加载失败，请刷新页面重试！");
      }
    }
  },
  error => {
    endLoading();
    console.log(error);
    window.$message.error("网络异常，请刷新页面重试！");
    return Promise.reject(error);
  }
);

export default http;

export const newApiPrefix = '/apiV2'
export const oldApiPrefix = '/old_api'
